package handlers

import (
	"github.com/golang-jwt/jwt/v4"
	"go-GameTimer-X/response"
	"net/http"
	"time"

	"go-GameTimer-X/app/services"
	"go-GameTimer-X/utils"

	"github.com/gin-gonic/gin"
)

// LoginHandler 登录处理
func LoginHandler(c *gin.Context) {
	var (
		username string
		password string
	)

	// 解析请求数据
	if c.Request.Method == http.MethodPost {
		// 表单绑定结构体
		var form struct {
			Username string `form:"username" binding:"required"`
			Password string `form:"password" binding:"required"`
		}

		if err := c.ShouldBind(&form); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
			return
		}
		username = form.Username
		password = form.Password
	} else {
		// 解析JSON数据
		type loginReq struct {
			Username string `json:"username" binding:"required"`
			Password string `json:"password" binding:"required"`
		}

		var req loginReq
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数错误"})
			return
		}

		username = req.Username
		password = req.Password
	}

	// 调用认证服务
	token, err := services.Login(username, password)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	// 设置 Cookie（可选）
	c.SetCookie("token", token, 3600, "/", "", false, true)

	// 返回成功响应
	c.JSON(http.StatusOK, gin.H{
		"token":  token,
		"expire": time.Now().Add(time.Second * time.Duration(86400)).Unix(),
	})
}

// RegisterHandler 注册处理
func RegisterHandler(c *gin.Context) {
	type registerReq struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	var req registerReq
	if err := c.ShouldBind(&req); err != nil {
		response.FailWithMessage("请求参数错误", c)
		return
	}

	if len(req.Password) < 6 {
		response.FailWithMessage("密码不能小于6位", c)
		return
	}

	err := services.Register(req.Username, req.Password)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	response.OkWithMessage("注册成功", c)
}

// RefreshTokenHandler 刷新 Token 处理
func RefreshTokenHandler(c *gin.Context) {
	tokenString := c.GetHeader("Authorization")
	if tokenString == "" {
		response.FailWith401(c)
		return
	}

	// 从配置文件中获取 JWT 配置
	secret := "your-secret-key" // 实际应用中应从配置中读取

	// 解析 JWT Token
	token, err := utils.ParseJWT(tokenString, secret)
	if err != nil || !token.Valid {
		response.FailWithMessage("无效的Token", c)
		return
	}

	claims := token.Claims.(jwt.MapClaims)
	userID := claims["sub"].(string)

	// 生成新的 Token
	newToken, err := utils.GenerateJWT(userID, secret, 86400)
	if err != nil {
		response.FailWithMessage("Token刷新失败", c)
		return
	}

	response.OkWithData(gin.H{
		"token":  newToken,
		"expire": claims["exp"],
	}, c)
	// todo 如果报错 则使用下面这个
	//response.OkWithData(map[string]interface{}{
	//	"token":  newToken,
	//	"expire": claims["exp"],
	//}, c)
}
